package net.expectx.micro.shop.controller.product;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiOperation;
import net.expectx.common.single.base.BaseConstants;
import net.expectx.common.single.base.BaseResult;
import net.expectx.micro.shop.common.AdminConstants;
import net.expectx.micro.shop.common.AdminResult;
import net.expectx.micro.shop.dao.bean.ProductCategory;
import net.expectx.micro.shop.dao.bean.ProductCategoryExample;
import net.expectx.micro.shop.rpc.api.ProductCategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author lijian
 */
@Controller
@RequestMapping(value = "/manager/productCategory")
public class ProductCategoryController  {
    private static final Integer ZERO=0;
    @Autowired
    private ProductCategoryService productCategoryService;

    @ApiOperation(value = "分类主页")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index( HttpServletRequest request) {

        return "product/category/index";
    }

    @ApiOperation(value = "新增分类")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(ModelMap modelMap) {
        return "product/category/modify";
    }
    @ApiOperation(value = "修改分类")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String update(@PathVariable("id") Long id, ModelMap modelMap) {
        ProductCategory productCategory = productCategoryService.selectByPrimaryKey(id);
        modelMap.put("productCategory", productCategory);
//        List<ProductType>productTypes=productTypeService.findByAttr("is_deleted=0","orders desc");
//        modelMap.put("productTypes",productTypes);
        return "product/category/modify";
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "1", value = "page") int page,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            HttpServletRequest request) {
        ProductCategoryExample productCategoryExample = new ProductCategoryExample();
        ProductCategoryExample.Criteria criteria = productCategoryExample.createCriteria();
        criteria.andIsDeletedEqualTo(AdminConstants.NO);

        /**
         * 分页
         */
        productCategoryExample.setPageIndex(page);
        productCategoryExample.setPageSize(limit);
        /**
         * 排序
         */
        productCategoryExample.setOrderByClause("id desc");

        List<ProductCategory> productCategorys = productCategoryService.selectByExample(productCategoryExample);
        List<Map> tree = new ArrayList<>();
        for(ProductCategory productCategory: productCategorys){
            Map<String, Object> map = Maps.newHashMapWithExpectedSize(7);
            map.put("id", productCategory.getId());
            map.put("pid", productCategory.getProductCategoryParentId());
            if (null == productCategory.getProductCategoryParentId()) {
                map.put("pid", "0");
            }
            map.put("name", productCategory.getProductCategoryName());
            tree.add(map);
        }
        JSONArray jsa = JSONArray.parseArray(JSONArray.toJSONString(tree));
        long total = productCategoryService.countByExample(productCategoryExample);
        Map<String, Object> result =  Maps.newHashMapWithExpectedSize(7);
        result.put("code", "0");
        result.put("count", total);
        result.put("is", true);
        result.put("msg", "");
        result.put("data", jsa);
        return result;
    }

    @ApiOperation(value = "新增分类")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(ProductCategory productCategory) {
        productCategory.setGmtCreate(System.currentTimeMillis());
        productCategory.setGmtModified(System.currentTimeMillis());
        productCategory.setIsDeleted(AdminConstants.NO);
        productCategory.setOrders(System.currentTimeMillis());
        return productCategoryService.insertSelective(productCategory);
    }

    @ApiOperation(value = "修改分类")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@PathVariable("id") Long id, ProductCategory productCategory) {
        productCategory.setGmtModified(System.currentTimeMillis());
        productCategory.setOrders(System.currentTimeMillis());
        return productCategoryService.updateByPrimaryKeySelective(productCategory);
    }

    @ApiOperation(value = "删除分类")
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public BaseResult delete(@PathVariable("ids") String ids) {
        List<String> idsStr = Arrays.asList(ids.split(","));
        List<Long> idList = new ArrayList<>();
        for (String s : idsStr) {
            idList.add(Long.valueOf(s));
        }
        ProductCategoryExample productCategoryExample =new ProductCategoryExample();
        ProductCategoryExample.Criteria criteria = productCategoryExample.createCriteria();
        criteria.andIsDeletedEqualTo(AdminConstants.NO);
        criteria.andProductCategoryParentIdIn(idList);
        List<ProductCategory> productCategories = productCategoryService.selectByExample(productCategoryExample);
        if(productCategories.isEmpty()){
            ProductCategoryExample productCategoryExample2 = new ProductCategoryExample();
            ProductCategoryExample.Criteria criteria2 = productCategoryExample2.createCriteria();
            criteria2.andIsDeletedEqualTo(AdminConstants.NO);
            criteria2.andIdIn(idList);
            return productCategoryService.physicalRemoveByExample(AdminConstants.YES,productCategoryExample2);
        }
        return new BaseResult(false,"存在下级,删除失败",null);
    }
    @ApiOperation(value = "分类获取")
    @RequestMapping(value = "/category", method = RequestMethod.GET)
    @ResponseBody
    public Object region(String id){
        List<Map>list=new ArrayList<>();
        ProductCategoryExample productCategoryExample = new ProductCategoryExample();
        ProductCategoryExample.Criteria criteria = productCategoryExample.createCriteria();
        criteria.andIsDeletedEqualTo(AdminConstants.NO);
        if (ZERO.equals(id)){
            criteria.andProductCategoryParentIdIsNull();
//            strWhere += " and  product_category_parent_id  is  null";
        }else{
            criteria.andProductCategoryParentIdEqualTo(Long.valueOf(id));
//            strWhere += "  and  product_category_parent_id="+id;
        }
        List <ProductCategory>productCategories=productCategoryService.selectByExample(productCategoryExample);

        ProductCategoryExample productCategoryExample2 = new ProductCategoryExample();
        productCategoryExample2.createCriteria().andIsDeletedEqualTo(AdminConstants.NO);
        List<ProductCategory> productCategories2 = productCategoryService.selectByExample(productCategoryExample2);

        for (ProductCategory productCategory:productCategories){
            Map map= Maps.newHashMapWithExpectedSize(7);
            map.put("id",productCategory.getId());
            map.put("pId",productCategory.getProductCategoryParentId());
            map.put("name",productCategory.getProductCategoryName());

            boolean flag = false;
            for (ProductCategory category : productCategories2) {
              if (category.getProductCategoryParentId()==productCategory.getId()){
                  flag=true;
              }
            }
            if (flag){
                map.put("isParent",true);
            }else {
                map.put("isParent",false);
            }
            list.add(map);
        }
        return list;
    }
    @ApiOperation(value = "获取树")
    @RequestMapping(value = "/treeGrid", method = RequestMethod.POST)
    @ResponseBody
    public Object treeGrid(@RequestParam(required = false, defaultValue = "0", value = "pageIndex") int pageIndex,
                           @RequestParam(required = false, defaultValue = "10", value = "pageSize") int pageSize,
                           String id){
        if (Strings.isNullOrEmpty(id)){
            id="0";
        }
        ProductCategoryExample productCategoryExample = new ProductCategoryExample();
        ProductCategoryExample.Criteria criteria = productCategoryExample.createCriteria();
        criteria.andIsDeletedEqualTo(AdminConstants.NO);
        criteria.andProductCategoryParentIdEqualTo(Long.valueOf(id));
        /**
         * 排序
         */
        productCategoryExample.setOrderByClause("id desc");
        List<ProductCategory> productCategories = productCategoryService.selectByExample(productCategoryExample);
        List<JSONObject>jsonObjects=new ArrayList<>();
        for (ProductCategory category:productCategories){
            JSONObject json=(JSONObject) JSON.toJSON(category);
            ProductCategoryExample productCategoryExample1 = new ProductCategoryExample();
            ProductCategoryExample.Criteria criteria1 = productCategoryExample1.createCriteria();
            criteria1.andIsDeletedEqualTo(AdminConstants.NO);
            criteria1.andProductCategoryParentIdEqualTo(category.getId());
            if (productCategoryService.countByExample(productCategoryExample1)>0){
                json.put("folder",1);
                json.put("isLeaf",false);
                json.put("expanded",false);
            }
            jsonObjects.add(json);

        }
        ProductCategoryExample productCategoryExample2 = new ProductCategoryExample();
        ProductCategoryExample.Criteria criteria2 = productCategoryExample2.createCriteria();
        criteria2.andIsDeletedEqualTo(AdminConstants.NO);
        criteria2.andProductCategoryParentIdEqualTo(0L);
        long total = productCategoryService.countByExample(productCategoryExample2);
        Map<String, Object> result =  Maps.newHashMapWithExpectedSize(7);
        result.put("total", total);
        result.put("data", jsonObjects);
        return jsonObjects;
    }

}
